package com.greenant.store.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.greenant.store.R;
import com.greenant.store.adapter.MyOrderListAdapter;
import com.greenant.store.bean.Order;
import com.greenant.store.bean.OrderList;
import com.greenant.store.bean.OrderStatusCode;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.service.RetrieveDataListener;
import com.greenant.store.utils.Const;
import com.greenant.store.utils.iLog;
import com.handmark.pulltorefresh.library.ILoadingLayout;

public class OrdersListFragment extends Fragment {
	private static final String TAG = "GoodsListFragment";

	/**
	 * 订单类型
	 */
	public static final int ORDER_TYPE_ALL = Order.ORDER_TYPE_ALL;
	
	public static final int ORDER_TYPE_UNSEND = OrderStatusCode.ORDER_PENDING.value();//未发货
	public static final int ORDER_TYPE_UNPAY = OrderStatusCode.ORDER_WAIT_FOR_PAY.value();//未付款
	public static final int ORDER_TYPE_UNRECEIVE = OrderStatusCode.ORDER_WAIT_FOR_SIGN.value();// 待收货，已配送和已配送至自提点和待收货
	public static final int ORDER_TYPE_REFUNDING = OrderStatusCode.ORDER_REFUNDING.value();// 退款中
	
	public static final int ORDER_TYPE_FINISHED = OrderStatusCode.ORDER_FINISHED.value();// 已完成
	public static final int ORDER_TYPE_CLOSED = OrderStatusCode.ORDER_CLOSED.value();// 已关闭

	private int orderType = ORDER_TYPE_ALL;
	private String userId;
	private final static String TAG_ORDER_TYPE = "orderType";
	private final static String TAG_USER_ID = "userId";

	private final int expectedCount = 20;

	private List<Order> list = new ArrayList<Order>();
	MyOrderListAdapter myOrderListAdapter;
	private int totalItemCounts = 0;
	private boolean isGettingData = false;

	private TextView noOrderListHint;
	private ListView orderlistView;
	private RelativeLayout nodataView;

	private Context mContext;
	

	public static OrdersListFragment newInstance(int orderType, String userId) {
		OrdersListFragment newFragment = new OrdersListFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(TAG_ORDER_TYPE, orderType);
		bundle.putString(TAG_USER_ID, userId);
		newFragment.setArguments(bundle);
		return newFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getArguments();
		if (bundle != null) {
			orderType = bundle.getInt(TAG_ORDER_TYPE, ORDER_TYPE_ALL);
			userId = bundle.getString(TAG_USER_ID);
		}
		registerReciver();
		mContext = this.getActivity().getApplicationContext();
	}

	private void registerReciver() {
		IntentFilter downloadManagerFilter = new IntentFilter();
		downloadManagerFilter.addAction(Const.ORDER_STATUS_CHANGED);
		this.getActivity().getBaseContext().registerReceiver(netManagerReceiver, downloadManagerFilter);
	}

	private BroadcastReceiver netManagerReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (myOrderListAdapter != null) {
				myOrderListAdapter.notifyDataSetChanged();
			}
		}

	};

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Bundle bundle = this.getArguments();
		if (bundle != null) {
			orderType = bundle.getInt(TAG_ORDER_TYPE, ORDER_TYPE_ALL);
			userId = bundle.getString(TAG_USER_ID);
		}
	

		View contentView = inflater.inflate(R.layout.fragment_orderlist, container, false);
		orderlistView = (ListView) contentView.findViewById(R.id.orderlist);
		// orderlistView.seton
		// orderlistView.setMode(Mode.PULL_DOWN_TO_REFRESH);
		initPullToRefreshListView();

	
		noOrderListHint = (TextView) contentView.findViewById(R.id.noOrderListHint);
		nodataView = (RelativeLayout) contentView.findViewById(R.id.nodataView);
		myOrderListAdapter = new MyOrderListAdapter(list, getActivity());
		orderlistView.setAdapter(myOrderListAdapter);

		orderlistView.setOnScrollListener(new AbsListView.OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if (totalItemCount < totalItemCounts && (firstVisibleItem + visibleItemCount) == (totalItemCount - 2)) {
					if (!isGettingData) {
						isGettingData = true;

						RetrieveDataAsyn.getInstance().getMyOrderByType(userId, orderType, list.size(), expectedCount,
								0, new RetrieveDataListener() {

							@Override
							public void dataRetrieved(int requestId, Object data) {
								if (data != null) {
									OrderList orderList = (OrderList) data;
									totalItemCounts = orderList.getTotalNum();
									list.addAll(orderList.getOrderList());
									myOrderListAdapter.notifyDataSetChanged();
								}
								isGettingData = false;
							}
						});

					}

				}
			}
		});
		getFirstData();
		return contentView;
	}

	public void getFirstData() {
		RetrieveDataAsyn.getInstance().getMyOrderByType(userId, orderType, 0, expectedCount, 0,
				new RetrieveDataListener() {

					@Override
					public void dataRetrieved(int requestId, Object data) {
						list.clear();
						refreshWithData();
						iLog.d(TAG, "onRefreshComplete:" + data);
						if (data != null) {

							OrderList orderList = (OrderList) data;
							totalItemCounts = orderList.getTotalNum();
							list.addAll(orderList.getOrderList());
							if (list.size() == 0) {
								refreshNoData();
							}
						} else {
							refreshNoData();
						}
						myOrderListAdapter.notifyDataSetChanged();
						// orderlistView.onRefreshComplete();
					}
				});
	}

	public void initPullToRefreshListView() {
		// ILoadingLayout startLabels = orderlistView
		// .getLoadingLayoutProxy(true, false);
		// startLabels.setPullLabel(mContext.getString(R.string.pull_to_refresh));//
		// 刚下拉时，显示的提示
		// startLabels.setRefreshingLabel(mContext.getString(R.string.pull_to_refreshing));//
		// 刷新时
		// startLabels.setReleaseLabel(mContext.getString(R.string.pull_to_refreshbegin));//
		// 下来达到一定距离时，显示的提示

		// ILoadingLayout endLabels = orderlistView.getLoadingLayoutProxy(
		// false, true);
		// endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
		// endLabels.setRefreshingLabel("正在载入...");// 刷新时
		// endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

		// // 设置下拉刷新文本
		// pullToRefresh.getLoadingLayoutProxy(false, true)
		// .setPullLabel("上拉刷新...");
		// pullToRefresh.getLoadingLayoutProxy(false, true).setReleaseLabel(
		// "放开刷新...");
		// pullToRefresh.getLoadingLayoutProxy(false, true).setRefreshingLabel(
		// "正在加载...");
		// // 设置上拉刷新文本
		// pullToRefresh.getLoadingLayoutProxy(true, false)
		// .setPullLabel("下拉刷新...");
		// pullToRefresh.getLoadingLayoutProxy(true, false).setReleaseLabel(
		// "放开刷新...");
		// pullToRefresh.getLoadingLayoutProxy(true, false).setRefreshingLabel(
		// "正在加载...");
	}

	public void refreshNoData() {
		noOrderListHint.setVisibility(View.VISIBLE);
		orderlistView.setVisibility(View.INVISIBLE);
		nodataView.setVisibility(View.INVISIBLE);
	}

	public void refreshWithData() {
		noOrderListHint.setVisibility(View.INVISIBLE);
		orderlistView.setVisibility(View.VISIBLE);
		nodataView.setVisibility(View.INVISIBLE);
	}

	@Override
	public void onDestroy() {
		this.getActivity().getBaseContext().unregisterReceiver(netManagerReceiver);
		super.onDestroy();
		Log.d(TAG, "MyStoreFragment-----onDestroy");
	}

}
